home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / SML⁄NJ 93+ / Documentation / examples / textbooks / four_lectures / lib.sml < prev    next >
Encoding:
Text File  |  1995-12-30  |  1.8 KB  |  68 lines  |  [TEXT/R*ch]

  1. signature LISTUTIL= 
  2.  sig
  3.   val isIn : ''a * ''a list -> bool
  4.   val union: ''a list * ''a list -> ''a list
  5.   val minus: ''a list * ''a list -> ''a list
  6.   val intersect: ''a list * ''a list -> ''a list
  7.   val map: ('a -> 'b) -> 'a list -> 'b list
  8.   val fold: (('a * 'b) -> 'b) -> 'b -> 'a list -> 'b
  9.   val zip: 'a list * 'b list -> ('a * 'b)list
  10.   exception Lookup
  11.   val lookup: (''a * 'b) list -> ''a -> 'b
  12.   exception Prefix
  13.   val prefix: 'a list * int -> 'a list
  14.  end;
  15.  
  16. functor List(): LISTUTIL=
  17. struct
  18.   fun isIn(x,[])= false
  19.     | isIn(x,hd::tl) = x = hd orelse isIn(x,tl)
  20.   fun union([],l) =l
  21.     | union(hd::tl,l) = if isIn(hd,l) then union(tl,l)
  22.                         else hd::union(tl,l)
  23.   fun minus([],l)= []
  24.     | minus(hd::tl,l) = if isIn(hd,l) then minus(tl,l)
  25.                         else hd::minus(tl,l)
  26.   fun intersect([],l) = []
  27.     | intersect(hd::tl, l) = if isIn(hd,l) then
  28.                                 hd::intersect(tl,l)
  29.                              else intersect(tl,l)
  30.   fun map f [] = []
  31.     | map f (hd::tl) = f hd :: map f tl
  32.  
  33.   fun fold f b [] = b
  34.     | fold f b (hd::tl) = f(hd,fold f b tl)
  35.  
  36.   fun zip([],l) = []
  37.     | zip(l,[]) = []
  38.     | zip(hd::tl, hd'::tl')= (hd,hd')::zip(tl,tl')
  39.  
  40.   exception Lookup
  41.   fun lookup [] x = raise Lookup
  42.     | lookup ((x,y)::tl) x'=
  43.         if x=x' then y else lookup tl x'
  44.  
  45.   exception Prefix
  46.   fun prefix(l,0) = []
  47.     | prefix([],n) = raise Prefix
  48.     | prefix((hd::tl),n)= hd::prefix(tl,n-1)
  49. end;
  50.  
  51.  
  52. signature PRINTUTIL =
  53. sig
  54.   val intToString: int -> string
  55.   val natToString: int -> string
  56. end;
  57.  
  58. functor Print():PRINTUTIL=
  59. struct
  60.   fun intToString(i:int)=  
  61.           (if i<0 then " -" else "")^ natToString (abs i)
  62.   and natToString(n:int)=
  63.       let val d = n div 10 in
  64.         if d = 0 then chr(ord"0" + n)
  65.         else natToString(d)^ chr(ord"0" + (n mod 10))
  66.       end
  67. end;
  68.